<!--
 * @Author: Tommy Chen
 * @Date: 2023-02-23
 * @LastEditors: Tommy Chen
 * @LastEditTime: 2023-07-18
 * @FilePath: /macc.admin.vue/src/views/monitor/voucherReport/index.vue
 * @Description: 802.1x用户列表
-->

<template>
  <div>
    <div class="voucher-header">
      <h3>{{ $t('voucherRpt.report') }}</h3>
      <rj-space class="space-between">
        <div class="time-select">
          <a-radio-group v-model="activeKey" @change="onChangeDate">
            <!-- 如果是选取时间段，则不需要change也能显示picker -->
            <a-radio-button
              @click="activeKey === 'pick' ? (pickShow = !pickShow) : ''"
              :value="item.value"
              v-for="item in dateBtnList"
              :key="item.value"
            >
              {{ item.text }}
            </a-radio-button>
          </a-radio-group>
          <div class="date-picker" v-if="pickShow">
            <a-range-picker
              @change="onPick"
              :format="dateFormat"
              :value="pickTime ? pickTime : null"
            />
            <div class="btn-group">
              <button
                :class="pickTime ? null : 'disabled'"
                :disabled="pickTime == null ? true : false"
                @click="pickOK"
              >
                {{ $t('arp.conmfirm') }}
              </button>
              <button @click="pickShow = false">{{ $t('arp.cancel') }}</button>
            </div>
          </div>
        </div>
      </rj-space>
    </div>
    <div class="table-data" ref="tableData">
      <rj-table
        ref="tableRef"
        rowKey="userMac"
        :loading="loading"
        :export="exportData"
        class="upgrade-device-list"
        :columns="voucherColumns"
        :data-source="voucherList"
        @refeshTable="refreshTable"
      >
        <template slot="price" slot-scope="text">
          {{ formatterPrice(text) }}
        </template>
        <template slot="activatedAmount" slot-scope="text">
          {{ formatterAmount(text) }}
        </template>
      </rj-table>
    </div>
  </div>
</template>
<script>
import { mapState } from 'vuex';
import { requestHttp, maccApi } from '@/utils';
import { RjTable, RjModal } from '@components';
import { downloadPDF } from '@utils/htmlToPdf';
export default {
  name: 'voucherReport',
  components: {
    'rj-table': RjTable,
  },

  data() {
    return {
      activeKey: 'day',
      loading: false,
      voucherList: [],
      dateFormat: 'YYYY/MM/DD HH:mm:ss',
      dateBtnList: [
        {
          value: 'day',
          text: this.$t('common.last1Day'),
        },
        {
          value: 'week',
          text: this.$t('dataInsight.last7days'),
        },
        {
          value: 'month',
          text: this.$t('dataInsight.last30days'),
        },
        {
          value: 'pick',
          text: this.$t('arp.custom'),
        },
      ],
      pickTime: null, // 格式为YYYYMMDD HHmmss
      pickShow: false,
      voucherColumns: [
        {
          title: this.$t('common.index'), // 编号 No
          align: 'center',
          key: 'no',
          dataIndex: 'no',
        },
        {
          title: this.$t('userManage.profileName'), // 名称 Package Name
          align: 'center',
          key: 'name',
          dataIndex: 'name',
        },
        {
          title: this.$t('userManage.profileModalPrice'), // 单价 Price
          align: 'right',
          dataIndex: 'price',
          key: 'price',
          scopedSlots: { customRender: 'price' },
        },
        {
          title: this.$t('dataInsight.num'), // 流量 Qty
          align: 'center',
          key: 'numberOfVouchersUnderProfile',
          dataIndex: 'numberOfVouchersUnderProfile',
        },
        {
          title: this.$t('voucherRpt.activateNum'), // 激活账号 Activated Accounts
          align: 'center',
          key: 'activatedConn',
          dataIndex: 'activatedConn',
        },
        {
          title: this.$t('voucherRpt.totalPrice'), // 总价 Total Price
          align: 'right',
          dataIndex: 'activatedAmount',
          key: 'activatedAmount',
          scopedSlots: { customRender: 'activatedAmount' },
        },
      ],
    };
  },
  mounted() {
    this.initDefaultDate();
    this.getVoucherList({});
  },
  computed: {
    ...mapState('Group', ['groupId', 'groupInfo']),
    ...mapState('User', ['tenantInfo', 'userInfo']),
  },
  methods: {
    //确认picker选取时间
    pickOK() {
      if (this.pickTime) {
        // 时间参数把后面的HHmmss去掉后再进行转换
        const start = this.toGetTime(this.pickTime[0].split(' ')[0]);
        // 结束当天的23:59:59
        const dayTime = (3600 * 24 - 1) * 1000;
        const end = this.toGetTime(this.pickTime[1].split(' ')[0]) + dayTime;
        this.getVoucherList({ loginStart: start, loginEnd: end });
        this.pickShow = false;
      }
    },
    //获取picker时间
    onPick(date, dateString) {
      if (dateString[0] == '' || dateString[1] == '') {
        this.pickTime = null;
      } else {
        let dateStr = [
          dateString[0].split(' ')[0] + ' 000000',
          dateString[1].split(' ')[0] + ' 235959',
        ];
        // 改为 YYYYMMDD HHmmss 对应格式后再赋值给pickTime,
        this.pickTime = dateStr.map((item) => {
          return item.replace(/\//g, '');
        });
      }
    },
    //默认初始时间
    initDefaultDate() {
      // 改为 YYYYMMDD HHmmss 对应格式后再赋值给pickTime,
      let dateStr = [
        this.toFormatTime(this.calltime('month').start) + ' 000000',
        this.toFormatTime(this.calltime('month').end) + ' 235959',
      ];
      this.pickTime = dateStr.map((item) => {
        return item.replace(/\//g, '');
      });
      console.log(this.pickTime);
    },
    // 切换时间
    onChangeDate() {
      if (this.activeKey !== 'pick') {
        this.pickShow = false;
        const start = this.toGetTime(this.calltime(this.activeKey).start);
        const end = this.toGetTime(this.calltime(this.activeKey).end);
        this.getVoucherList({ loginStart: start, loginEnd: end });
      } else {
        this.pickShow = !this.pickShow;
      }
    },
    // 将时间转换成getTime()格式
    toGetTime(timeString) {
      // 分别提取年、月、日
      var year = parseInt(timeString.substr(0, 4));
      var month = parseInt(timeString.substr(4, 2)) - 1; // 在JavaScript中，月份从0开始，所以减1
      var day = parseInt(timeString.substr(6, 2));
      // 创建Date对象
      var date = new Date(year, month, day);
      // 获取时间戳
      return date.getTime();
    },
    // 导出
    async exportData() {
      // 导出 excell
      // this.$refs.tableRef.exportData(this.voucherList, {
      //   filename: this.$t('voucherRpt.report'),
      //   autoWidth: true,
      // });

      // 导出pdf
      var btns = document.querySelector('.table-operate');
      // 防止将按钮导出
      btns.style.opacity = 0;
      const result = await downloadPDF(
        this.$refs.tableData,
        this.$t('voucherRpt.report')
      );
      if (result !== null || result !== undefined) {
        btns.style.opacity = 1;
      }
    },
    // 刷新
    refreshTable() {
      if (this.activeKey == 'pick') {
        this.pickOK();
      } else {
        this.onChangeDate();
      }
    },
    // 表格初始化
    async getVoucherList(params) {
      this.loading = true;
      // 获取当天0点的时间
      let currentDate = new Date();
      currentDate.setHours(0, 0, 0, 0);
      //响应接口
      const res = await requestHttp({
        api: maccApi.PROFILE_LIST_GET_API,
        method: 'GET',
        replaces: {
          groupId: this.groupInfo.groupId,
          tenantName: this.tenantInfo.tenantName,
        },
        querys: {
          page: 'page' in params ? params.page : 1,
          loginStart:
            'loginStart' in params
              ? params.loginStart
              : currentDate.getTime() - 3600 * 1000 * 24,
          loginEnd:
            'loginEnd' in params ? params.loginEnd : currentDate.getTime(),
          profileStatus:
            'profileStatus' in params ? params.profileStatus : 'all',
          name: 'name' in params ? params.name : '',
          order: 'order' in params ? params.order : 'asc',
        },
      });
      const data = res.voucherData.list;
      let total = {
        no: this.$t('wioOptimize.roamTotal'),
        name: '',
        description: '',
        price: null,
        numberOfVouchersUnderProfile: 0,
        activatedConn: 0,
        activatedAmount: 0,
      };
      let activated = [],
        noActivated = [];
      //  按总价排序
      data.sort(function (a, b) {
        return b.activatedAmount * 1 - a.activatedAmount * 1;
      });
      // 给上编号，并按要求计算激活账号和总价等等
      data.map((item, index) => {
        item.no = index + 1;
        item.key = ++index;
        if ('activatedAmount' in item) {
          if (
            item.numberOfVouchersUnderProfile !== 0 ||
            item.activatedConn !== 0
          ) {
            activated.push(item);
            total.numberOfVouchersUnderProfile +=
              item.numberOfVouchersUnderProfile;
            total.activatedConn += item.activatedConn;
          }
          item.activatedAmount = item.activatedAmount * 1;
          total.activatedAmount += item.activatedAmount;
        } else {
          if (
            item.numberOfVouchersUnderProfile !== 0 ||
            item.activatedConn !== 0
          ) {
            noActivated.push(item);
            total.numberOfVouchersUnderProfile +=
              item.numberOfVouchersUnderProfile;
            total.activatedConn += item.activatedConn;
          }
        }
      });
      this.voucherList = [...activated, ...noActivated];
      // 如果存在data，将total push到最后一行
      if (data.length) {
        this.voucherList.push(total);
      }
      this.loading = false;
    },
    // 将时间字符串格式化为YYYY/MM/DD
    toFormatTime(timeString) {
      return `${timeString.slice(0, 4)}/${timeString.slice(
        4,
        6
      )}/${timeString.slice(6, 8)}`;
    },
    //获取日期参数
    getParamsTime(date, type) {
      let nowDate = new Date(date);
      let year = nowDate.getFullYear();
      let month =
        nowDate.getMonth() + 1 < 10
          ? '0' + (nowDate.getMonth() + 1)
          : nowDate.getMonth() + 1;
      let day =
        nowDate.getDate() < 10 ? '0' + nowDate.getDate() : nowDate.getDate();
      let hour =
        nowDate.getHours() < 10 ? '0' + nowDate.getHours() : nowDate.getHours();
      let minutes =
        nowDate.getMinutes() < 10
          ? '0' + nowDate.getMinutes()
          : nowDate.getMinutes();
      let timestr =
        type == 'date' ? `${year}${month}${day}` : `${hour}:${minutes}`;
      return timestr;
    },
    // 获取时间范围
    calltime(type) {
      let start;
      let end = this.getParamsTime(new Date().getTime(), 'date');
      if (type === 'day') {
        start = this.getParamsTime(
          new Date().getTime() - 24 * 3600 * 1000,
          'date'
        );
      }
      if (type === 'week') {
        start = this.getParamsTime(
          new Date().getTime() - 7 * 24 * 3600 * 1000,
          'date'
        );
      }
      if (type === 'month') {
        start = this.getParamsTime(
          new Date().getTime() - 30 * 24 * 3600 * 1000,
          'date'
        );
      }
      return { start, end };
    },
    formatterPrice(value, row, index) {
      if (value) {
        if (value == 0) {
          return '0.00';
        } else {
          return value.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
        }
      } else {
        return '';
      }
    },
    formatterAmount(value, row, index) {
      if (value) {
        if (value == 0) {
          return '0.00';
        } else {
          return value.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
        }
      } else {
        return '0.00';
      }
    },
  },
};
</script>
<style lang="less" scoped>
.voucher-header {
  width: 100%;
  height: 54px;
  line-height: 54px;
  padding: 0 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;

  & h3 {
    line-height: 18px;
    display: inline-block;
    border-left: 3px solid #2b6afd;
    padding-left: 12px;
    font-size: 16px;
    color: #262626;
    vertical-align: middle;
  }

  .time-select {
    margin-left: auto;
    white-space: nowrap;
    height: 32px;
    line-height: 54px;
    box-sizing: content-box;

    .date-picker {
      width: 324px;
      height: 110px;
      padding: 10px;
      box-shadow: 0px 0px 4px 0px rgba(0, 0, 0, 0.5);
      background-color: #fff;
      border-radius: 4px;
      margin-top: 4px;
      position: absolute;
      z-index: 99;
      right: 16px;

      .btn-group {
        width: 100%;
        height: 32px;
        display: flex;
        justify-content: left;

        & button {
          margin-right: 10px;
          width: 76px;
          height: 32px;
          line-height: 32px;
          border-radius: 4px;
          outline: none;
          border: 1px solid #2b6afd;
          color: #2b6afd;
          background-color: #fff;
          font-size: 12px;

          &:hover {
            cursor: pointer;
            background-color: #2b6afd;
            color: #fff;
          }
        }

        .disabled {
          opacity: 0.6;

          &:hover {
            cursor: not-allowed !important;
            background-color: #fff !important;
            color: #2b6afd !important;
          }
        }
      }
    }

    input[type='radio'] + label {
      font-weight: 400;
      margin-right: 20px;
      margin-left: 8px;
    }
  }
}

.table-data {
  width: 100%;
  height: auto;
  margin-top: 20px;
  padding: 0 15px 15px 15px;
  box-sizing: border-box;
}

.space-between {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.refreshBtn {
  margin-left: 30px;
  margin-right: 6px;
}

.input {
  width: 280px;
}
</style>
